package com.zhoupu.integrated.file.service.impl;

import com.zhoupu.integrated.file.config.S3Config;
import com.zhoupu.integrated.file.service.IFileDownloadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import software.amazon.awssdk.core.ResponseInputStream;
import software.amazon.awssdk.core.sync.ResponseTransformer;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;

import java.io.InputStream;
import java.nio.file.Paths;

/**
 * 文件下载实现类
 *
 * @author Zhouyongli
 * @date 2025/11/12 17:40
 */
@Service
public class FileDownloadServiceImpl implements IFileDownloadService {

    @Autowired
    private S3Config s3Config;

    @Autowired
    private S3Client s3Client;

    /**
     * 下载文件到本地
     * @param remotePath  远程文件路径
     */
    public String downloadFile(String remotePath) {

        GetObjectRequest getObjectRequest = GetObjectRequest.builder()
                .bucket(s3Config.getBucket())
                .key(remotePath)
                .build();

        // 获取项目根目录
        String projectRootPath = System.getProperty("user.dir");

        // 获取原始文件名
        String originalFileName = remotePath.substring(remotePath.lastIndexOf('/') + 1);
        String fileExtension = originalFileName.contains(".") ? originalFileName.substring(originalFileName.lastIndexOf('.')) : "";
        String fileNameWithoutExt = originalFileName.contains(".") ? originalFileName.substring(0, originalFileName.lastIndexOf('.')) : originalFileName;

        // 使用时间戳生成新的文件名
        String timestamp = String.valueOf(System.currentTimeMillis());
        String newFileName = fileNameWithoutExt + "_" + timestamp + fileExtension;

        // 构建完整的本地文件路径，确保下载到项目根目录
        String fullLocalFilePath = Paths.get(projectRootPath, newFileName).toString();

        s3Client.getObject(getObjectRequest, Paths.get(fullLocalFilePath));

        return fullLocalFilePath;

    }

    /**
     * 下载文件为字节数组
     * @param remotePath  远程文件路径
     */
    public byte[] downloadBytes(String remotePath) {
        GetObjectRequest getObjectRequest = GetObjectRequest.builder()
                .bucket(s3Config.getBucket())
                .key(remotePath)
                .build();

        return s3Client.getObjectAsBytes(getObjectRequest).asByteArray();
    }




    /**
     * 下载文件为输入流
     * @param remotePath  远程文件路径
     */
    public ResponseInputStream<?> downloadFileInputStream(String remotePath) {
        GetObjectRequest getObjectRequest = GetObjectRequest.builder()
                .bucket(s3Config.getBucket())
                .key(remotePath)
                .build();

        return s3Client.getObject(getObjectRequest);

    }
}
